// pages/navigate-to-page/receive-page/receive-page.js
// 引入htm相关方法
// 音频
const htmAudio = require('../../util/htm-weixin/audio');
// 上传文件
const htmUploadFile = require('../../util/htm-weixin/upload-file');
// 下载文件
const htmDownloadFile = require('../../util/htm-weixin/download-file');
// 文件管理
const htmFileManager = require('../../util/htm-weixin/file-manager');
// 相册或者拍照
const htmImageAlbumCamera = require('../../util/htm-weixin/image-album-camera');
// 网络
const htmNetwork = require('../../util/htm-weixin/network');
// 打电话
const htmPhone = require('../../util/htm-weixin/phone');
// 录音
const htmRecorder = require('../../util/htm-weixin/recorder');
// 扫描
const htmScan = require('../../util/htm-weixin/scan');
// 存储
const htmStorage = require('../../util/htm-weixin/storage');
// 系统信息
const htmSystemInfo = require('../../util/htm-weixin/system-info');
// 设备信息
const htmDeviceInfo = require('../../util/htm-weixin/device-info');
// 第三方页面
const htmThird = require('../../util/htm-weixin/third');
// 振动
const htmVibrate = require('../../util/htm-weixin/vibrate');
// wifi
const htmWifi = require('../../util/htm-weixin/wifi');

const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 是否是第三方页面
    thirdFlag:false,
    // 限制传递最大长度
    dataSizeLimit:249,
    // 是否显示加载框
    isShowFlag:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.isShowFlag = true;
    let params = decodeURIComponent(options.params) // 解码
    let messageInfo = JSON.parse(params);
    app.transferList = app.transferList.concat(messageInfo);
    if( app.transferList.length > 0){
      this.selectionMethod(app.transferList[0])
    }
  },

  onShow(){
    // wx.showLoading();
  },

  onHide(){
    // wx.hideLoading()
    this.data.isShowFlag = false;
  },

  /**
   * 根据消息对象调用对应方法
   * @param { object } messageInfo 消息对象
   * @param { string } callbackID 方法回调Id
   * @param { string } action 对应模块名称
   * @param { string } module 对应方法名称
   * @param { object } data 调用方法所需的参数
   */
  async selectionMethod(messageInfo) {
    console.log('messageInfo',messageInfo);
    let thirdInfo = {};
    let that = this;
    // htm中规定的callback体，
    let returnInfo = {
      callbackID:messageInfo.callbackID,
      status: '1', // 状态码，1代表执行成功，触发success；空值||其他值，触发fail
      message: {}, // 回传值，success时，回调值
      statusMessage: {} // 回传值， fail||complete时触发
    };
    // 携带过来的参数
    let paramsInfo = JSON.parse(messageInfo.data);
    switch (messageInfo.module + ":" + messageInfo.action) {
      // 拍照实现
      case 'camera:takePhoto':
        await htmImageAlbumCamera.chooseMedia({
            sourceType: ['camera'],
            sizeType: paramsInfo.sizeType
          })
          .then((result) => {
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              let pictureImageSize = JSON.stringify(result).length;
              let times = pictureImageSize / (that.data.dataSizeLimit * 1000);
              let returnList = that.cutBase64String(result,times);
              returnInfo.message.data = returnList;
            }
          })
          .catch((err) => {
            console.log('err', err);
          });
        break;
        // 相册选择实现
      case 'album:chooseImage':
        await htmImageAlbumCamera.chooseMedia({
            count: paramsInfo.count,
            sourceType: ['album'],
            sizeType: paramsInfo.sizeType
          })
          .then((result) => {
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              let pictureImageSize = JSON.stringify(result).length;
              let times = pictureImageSize / (that.data.dataSizeLimit * 1000);
              let returnList = that.cutBase64String(result,times);
              returnInfo.message.data = returnList;
            }
          })
          .catch((err) => {
            console.log('err', err);
          });
        break;
        //  聊天记录中选择
      case 'upload_file:chatFileUpload':
        await htmUploadFile.uploadChatFile({
          count: paramsInfo.count,
          type: paramsInfo.type,
          url: paramsInfo.url,
          httoken: paramsInfo.httoken,
          bucket: paramsInfo.bucket,
          object: paramsInfo.object,
        }).then((result) => {
          if (result.errno) {
            returnInfo.status = result.errno;
            returnInfo.statusMessage.data = result.errMsg;
          } else {
            returnInfo.message.data = result;
          }
        }).catch((err) => {
          console.log(err);
        });
        break;
        // 文件上传
      case 'upload_file:uploadFile':
        await htmUploadFile.uploadBatchFile({
          url: paramsInfo.url,
          httoken: paramsInfo.httoken,
          bucket: paramsInfo.bucket,
          object: paramsInfo.object,
          tempFilePath: paramsInfo.tempFilePath,
        }).then((result) => {
          if (result.errno) {
            returnInfo.status = result.errno;
            returnInfo.statusMessage.data = result.errMsg;
          } else {
            returnInfo.message.data = result;
          }
        }).catch((err) => {
          console.log(err);
        });
        break;
        // 文件下载
      case 'download_file:downloadFile':
        await htmDownloadFile.downloadFile({
          url: paramsInfo.url,
          path: paramsInfo.path,
          name: paramsInfo.fileName,
        }).then((result) => {
          if (result.errno) {
            returnInfo.status = result.errno;
            returnInfo.statusMessage.data = result.errMsg;
          } else {
            returnInfo.message.data = result;
          }
        }).catch((err) => {
          console.log(err);
        });
        break;
        // 获取文件管理器
      case 'file_manager:getWeixinDirectory':
        await htmFileManager.getFileDirectory()
          .then((result) => {
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch((err) => {
            console.log('err', err);
          });
        break;
        // 检验文件是否存在
      case 'file_manager:access':
        await htmFileManager.accessFile(paramsInfo.path)
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch((err) => {
            console.log('err', err);
          })
        break;
        // 创建目录
      case 'file_manager:mkdir':
        await htmFileManager.mkdirFile(paramsInfo.path)
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch((err) => {
            console.log('err', err);
          })
        break;
        // 删除文件
      case 'file_manager:delete':
        await htmFileManager.deleteFile(paramsInfo.pathName)
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch((err) => {
            console.log('err', err);
          })
        break;
       // 获取文件信息
      case 'file_manager:getFile':
        await htmFileManager.getFileInfo(paramsInfo.pathName)
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch((err) => {
            console.log('err', err);
          })
        break;
        // 打开文件
      case 'file_manager:openFile':
        await htmFileManager.previewFile(paramsInfo.pathName)
          .then((result) => {
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch((err) => {
            console.log('err', err);
          });
        break;
        // 拨打电话
      case 'phone:makePhoneCall':
        await htmPhone.makePhoneCall(paramsInfo.phoneNumber)
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 获取系统信息
      case 'system_info:getSystemInfo':
        await htmSystemInfo.getSystemInfo()
          .then((result) => {
            console.log(result);
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 获取设备信息
      case 'device_info:getDeviceInfo':
        await htmDeviceInfo.getDeviceInfo()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 短振动
      case 'vibrate:short':
        await htmVibrate.vibrateShort()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 长振动
      case 'vibrate:long':
        await htmVibrate.vibrateLong()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 开始录音
      case 'recorder:start':
        await htmRecorder.startRecorder({
            duration: paramsInfo.duration,
            sampleRate: paramsInfo.sampleRate,
            numberOfChannels: paramsInfo.numberOfChannels,
            encodeBitRate: paramsInfo.encodeBitRate,
            format: paramsInfo.format,
            audioSource: paramsInfo.audioSource,
            returnData: paramsInfo.returnData,
          })
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 暂停录音
      case 'recorder:pause':
        await htmRecorder.pauseRecorder()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 继续录音
      case 'recorder:resume':
        await htmRecorder.resumeRecorder()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 结束录音
      case 'recorder:stop':
        await htmRecorder.stopRecorder()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 初始化音频
      case "audio:creatWeixinAudio":
        await htmAudio.createAudioContext(paramsInfo)
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 播放音频
      case "audio:play":
        await htmAudio.playAudio()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 暂停音频
      case "audio:pause":
        await htmAudio.pauseAudio()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 结束播放
      case "audio:stop":
        await htmAudio.stopAudio()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 跳转播放
      case "audio:seek":
        await htmAudio.seekRecorder(paramsInfo.position)
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 销毁音频实例
      case "audio:destroy":
        await htmAudio.destroyAudio()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message.data = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 开启wifi
      case "wifi:startWifi":
        await htmWifi.startWifi()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 获取wifi列表
      case "wifi:getWifiList":
        await htmWifi.getWifiList()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 关闭wifi
      case "wifi:stopWifi":
        await htmWifi.stopWifi()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 获取当前网络类型
      case "network:getNetWorkType":
        await htmNetwork.getNetWorkType()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 调用扫描
      case "scan:scan":
        await htmScan.scanCode()
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 存储用户信息
      case "user:login":
        htmStorage.setStorage('userInfo',paramsInfo);
        htmStorage.getStorage('userList')
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              htmStorage.setStorage('userList',[paramsInfo.user]);
            } else {
              if (!result.includes(paramsInfo.user)) {
                result.push(paramsInfo.user);
                htmStorage.setStorage('userList',result);
              }
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 获取用户信息
      case "user:getUser":
        await htmStorage.getStorage('userInfo')
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 获取用户列表
      case "user:getUserList":
        await htmStorage.getStorage('userList')
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 设置MQ信息
      case "mq_config:setMQConfig":
        await htmStorage.setStorage('MQConfigInfo',paramsInfo)
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 清除MQ信息
      case "mq_config:clearMQConfig":
        await htmStorage.removeStorage('MQConfigInfo')
          .then((result) => {
            // 存在errno表示调用失败，回传失败的值
            if (result.errno) {
              returnInfo.status = result.errno;
              returnInfo.statusMessage.data = result.errMsg;
            } else {
              returnInfo.message = result;
            }
          })
          .catch(err => {
            console.log('err', err);
          });
        break;
        // 设置导航栏颜色
      case "third:setStatusBarColor":
        // 修改web-view的顶部导航栏值
        app.statusBarInfo.statusBarFlag = "Y";
        app.statusBarInfo.statusBarColor = paramsInfo.color;
        break;
        // 重新加载页面
      case "third:reload":
        wx.reLaunch({
          url: "/pages/navigate-to-page/navigate-to-page"
        })
        break;
        // 新建web-view页面
      case "third:openPage":
        console.log('-----------新建第三方页面-----------');
        console.log('参数',paramsInfo);
        that.data.thirdFlag = true;
        thirdInfo = paramsInfo;
        // wx.navigateTo({
        //   url: '/pages/navigate-to-page/third-party/third-party?params=' + encodeURIComponent(JSON.stringify(paramsInfo)),
        // })
        break;
      default:
        console.error('未发现方法：',messageInfo.module+":"+messageInfo.action);
        break;
    };
    // 跳转回web页面
    if(messageInfo.callbackID != '' && messageInfo.callbackID != ' '){
      app.resultList.push(returnInfo);
    } 
    app.transferList.shift()
    if(app.transferList.length > 0){
      this.selectionMethod(app.transferList[0])
    }else{
      if(that.data.thirdFlag){
        that.data.thirdFlag = false;
        wx.navigateBack();
        wx.navigateTo({
          url: '/pages/third-party/third-party?params=' + encodeURIComponent(JSON.stringify(thirdInfo)),
        })
      }else{
        if (app.statusBarInfo && app.statusBarInfo.statusBarFlag == 'Y') {
          wx.setNavigationBarColor({
            frontColor: app.statusBarInfo.statusBarColor == '#ffffff' ? '#000000' : '#ffffff',
            backgroundColor: app.statusBarInfo.statusBarColor,
            success (res) {
              console.log(res)
            },
            fail:(err)=>{
              console.error(err);
            }
          })
        }
        wx.navigateBack(); 
      }
    }   
  },

  /**
   * 图片base64切片
   * 图片转base64之后数据过大时，采用切片回传
   * @param { string } base64Str base64数据流
   * @param { number } times 所需切片数量
   */
  cutBase64String(base64Str, times) {
    let returnList = [];
    // 计算需要截取的字节数
    const byteLength = (this.data.dataSizeLimit * 1000);
    // 将base64字符串转换为二进制字符串
    const binaryStr = JSON.stringify(base64Str);;
    // 截取指定字节数的字符串
    for(let i=0;i<Math.ceil(times);i++){
      let cutStr = binaryStr.substring(i*byteLength, (i+1)*byteLength); 
      returnList.push(cutStr)
    }
    // 将截取的二进制字符串重新转换为base64字符串
    return returnList;
  }
})